<?php 
namespace app\api\controller;
use think\Request;
use think\facade\Session;
class User extends Base{

	public function login(){
		if( $this->request->isPost() || $this->request->isAjax() ){
			$username = $this->request->param('username','trim');
			$password = encrypt($this->request->param('password','trim'));
			$user = db('user')->where('username = "'.$username.'" AND password = "'.$password.'"')->find();
			if(!$user){
				$data['status'] = 0;
				$data['msg'] = '用户名或密码不正确！';
				return returnJson(200,$data);	
			}
			$d['id'] = $user['id'];
			$d['username'] = $user['username'];
			Session::set('user',$d);
			$data['status'] = 1;
			$data['msg'] = '登录成功！';
			$data['user'] = json_encode($d,JSON_UNESCAPED_UNICODE);
			return returnJson(200,$data);
		}
	}

	public function logout(){
		session(null);
		return returnJson(200,[],'已退出！');
	}
	public function register(){
		if( $this->request->isPost() || $this->request->isAjax() ){
			$add['username'] = $this->request->param('username','trim');
			$add['password'] = encrypt($this->request->param('password','trim'));
			$count = db('user')->where('username = "'.$add['username'].'"')->count();
			if($count>0){
				$data['status'] = 0;
				$data['msg'] = '已经存在该用户名！';
				return returnJson(200,$data);	
			}
			$add['create_time'] = time();
			$id = db('user')->insertGetId($add);
			if($id > 0){
				$d['id'] = $id;
				$d['username'] = $add['username'];
				Session::set('user',$d);
				$data['status'] = 1;
				$data['msg'] = '注册成功！';
				$data['user'] = json_encode($d,JSON_UNESCAPED_UNICODE);
				return returnJson(200,$data);
			}else{
				$data['status'] = 0;
				$data['msg'] = '注册失败！';
				return returnJson(200,$data);
			}
		}
	}
}